package com.fenxiangle.yueding.feature.mine.view;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.vod.upload.VODSVideoUploadCallback;
import com.alibaba.sdk.android.vod.upload.VODSVideoUploadClient;
import com.alibaba.sdk.android.vod.upload.VODSVideoUploadClientImpl;
import com.alibaba.sdk.android.vod.upload.model.SvideoInfo;
import com.alibaba.sdk.android.vod.upload.session.VodHttpClientConfig;
import com.alibaba.sdk.android.vod.upload.session.VodSessionCreateInfo;
import com.fenxiangle.yueding.R;
import com.fenxiangle.yueding.common.widget.dialog.ActionSheetDialog;
import com.fenxiangle.yueding.common.widget.dialog.OnOperItemClickL;
import com.fenxiangle.yueding.common.widget.popupwindow.PopupWindowList;
import com.fenxiangle.yueding.common.widget.popupwindow.PopupWindowProgress;
import com.fenxiangle.yueding.common.widget.util.FullyGridLayoutManager;
import com.fenxiangle.yueding.entity.bo.UserCenterBo;
import com.fenxiangle.yueding.feature.common.view.MainActivity;
import com.fenxiangle.yueding.feature.mine.contract.MineContract;
import com.fenxiangle.yueding.feature.mine.dependencies.mine.DaggerMineComponent;
import com.fenxiangle.yueding.feature.mine.dependencies.mine.MinePresenterModule;
import com.fenxiangle.yueding.feature.mine.view.adapter.GridImageAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.rxbus2.RxBus;
import com.luck.picture.lib.rxbus2.Subscribe;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.SPUtil;
import com.suozhang.framework.utils.T;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.chad.library.adapter.base.listener.SimpleClickListener.TAG;
import static com.fenxiangle.yueding.common.util.FileUtil.getVideoThumb;
import static com.fenxiangle.yueding.common.util.FileUtil.saveBitmap;
import static com.fenxiangle.yueding.feature.mine.view.VedioFragment.SELECT_KEY;

public class UploadVedioActivity extends BaseActivity implements OnOperItemClickL, MineContract.View {


    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.upload_dec)
    EditText uploadDec;

    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    @BindView(R.id.btn_upload)
    TextView btnUpload;
    private ActionSheetDialog dialog;
    private UserCenterBo userCenterBo;
    private GridImageAdapter adapter;
    private String mCoverFile = "";
    private String mVedioFile = "";
    List<LocalMedia> selectList;


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_upload_vedio;
    }

    @Override
    protected void initInjector() {
        DaggerMineComponent.builder().minePresenterModule(new MinePresenterModule(this)).build().inject(this);
    }


    @Inject
    MineContract.Presenter mPresenter;
    private int position;
    VODSVideoUploadClient vodsVideoUploadClient;
    LocalMedia localMedia;

    @Override
    protected void initView() {
        initToolBar(mToolbar, "上传视频", true, true);
        //1.初始化短视频上传对象
        vodsVideoUploadClient = new VODSVideoUploadClientImpl(UploadVedioActivity.this);
        userCenterBo = (UserCenterBo) getIntent().getSerializableExtra("userCenterBo");
        position = (int) SPUtil.get(this,SELECT_KEY, 0);
        localMedia = (LocalMedia) getIntent().getSerializableExtra("localMedia");
        mVedioFile = getIntent().getStringExtra("videoPath");
        mCoverFile = getIntent().getStringExtra("imagePath");
        vodsVideoUploadClient.init();
        final String[] stringItems = {"拍摄", "从手机相册选择"};
        dialog = new ActionSheetDialog(this, stringItems, null);
        dialog.isTitleShow(false);
        dialog.setOnOperItemClickL(this);
        initVedioAdapter();
        if (localMedia != null) {
            selectList.add(localMedia);
            adapter.setList(selectList);
            adapter.notifyDataSetChanged();
        } else {
            if (!TextUtils.isEmpty(mVedioFile)) {
                selectList = new ArrayList<>();
                LocalMedia data = new LocalMedia();
                data.setPath(mVedioFile);
                data.setPictureType("video/mp4");
                data.setDuration(getVideoMediaPlayer(new File(mVedioFile)).getDuration());
                selectList.add(data);
                adapter.setList(selectList);
                adapter.notifyDataSetChanged();
            }
        }

    }




    private MediaPlayer getVideoMediaPlayer(File file) {
        try {
            return MediaPlayer.create(this, Uri.fromFile(file));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    PopupWindowProgress popupWindowProgress;

    @Override
    protected void initData() {

    }


    @OnClick({R.id.btn_upload})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.btn_upload:
                if (TextUtils.isEmpty(uploadDec.getText().toString())) {
                    T.showShort("请输入简介");
                    return;
                }

                if (TextUtils.isEmpty(mVedioFile)) {
                    T.showShort("请上传视频");
                    return;
                }

                if (popupWindowProgress == null) {
                    popupWindowProgress = new PopupWindowProgress(UploadVedioActivity.this);
                    popupWindowProgress.showMoreWindow();
                }
                uploadFile(mVedioFile);
                break;

        }
    }


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 20005) {
//            selectList = new ArrayList<>();
//            selectList = PictureSelector.obtainMultipleResult(data);
//            adapter.setList(selectList);
//            adapter.notifyDataSetChanged();
//
//            for (int i = 0; i < selectList.size(); i++) {
//                if (!TextUtils.isEmpty(selectList.get(i).getPath())) {
//                    mVedioFile = selectList.get(i).getPath();
//                }
//            }
//            if (!TextUtils.isEmpty(mVedioFile)) {
//                Bitmap bitmap = getVideoThumb(mVedioFile);
//                mCoverFile = saveBitmap(this, bitmap);
//            }
//
//        }
    }


    public void uploadFile(String path) {
        //参数请确保存在，如不存在SDK内部将会直接将错误throw Exception
// 文件路径保证存在之外因为Android 6.0之后需要动态获取权限，请开发者自行实现获取"文件读写权限".
        VodHttpClientConfig vodHttpClientConfig = new VodHttpClientConfig.Builder()
                .setMaxRetryCount(2)//重试次数
                .setConnectionTimeout(15 * 1000)//连接超时
                .setSocketTimeout(15 * 1000)//socket超时
                .build();
        //构建短视频VideoInfo,常见的描述，标题，详情都可以设置
        SvideoInfo svideoInfo = new SvideoInfo();
        svideoInfo.setTitle(new File(path).getName());
        svideoInfo.setDesc(uploadDec.getText().toString());
        svideoInfo.setCateId(1);
        //构建点播上传参数(重要)
        if (userCenterBo == null) {
            T.showShort("获取数据失败");
            return;
        }
        if (!popupWindowProgress.isShowing()) {
            popupWindowProgress.setShow(recyclerView);
        }
        if (!new File(mCoverFile).exists()) {
            T.showShort("图片文件不存在");
            return;
        }

        if (!new File(path).exists()) {
            T.showShort("视频文件不存在");
            return;
        }
        try {

            VodSessionCreateInfo vodSessionCreateInfo = new VodSessionCreateInfo.Builder()
                    .setImagePath(mCoverFile)//图片地址
                    .setVideoPath(path)//视频地址
                    .setAccessKeyId(userCenterBo.getAccessKeyId())//临时accessKeyId
                    .setAccessKeySecret(userCenterBo.getAccessKeySecret())//临时accessKeySecret
                    .setSecurityToken(userCenterBo.getSecurityToken())//securityToken
                    .setExpriedTime(System.currentTimeMillis() + "")//STStoken过期时间
                    .setRequestID(userCenterBo.getRequestId())//requestID，开发者可以传将获取STS返回的requestID设置也可以不设.
                    .setIsTranscode(true)//是否转码.如开启转码请AppSever务必监听服务端转码成功的通知
                    .setSvideoInfo(svideoInfo)//短视频视频信息
                    .setVodHttpClientConfig(vodHttpClientConfig)//网络参数
                    .build();

            vodsVideoUploadClient.uploadWithVideoAndImg(vodSessionCreateInfo, new VODSVideoUploadCallback() {
                @Override
                public void onUploadSucceed(String videoId, String imageUrl) {
                    UploadVedioActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

//                            T.showLong("onUploadSucceed" + "videoId:" + videoId + "imageUrl" + imageUrl);
                            HashMap<String, String> hashMap = new HashMap<>();
                            try {
                                hashMap.put("videoDescribe", uploadDec.getText().toString());
                                hashMap.put("videoId", videoId);
                                hashMap.put("videoType", position+"");
                                mPresenter.upload_user_video(new File(mCoverFile), hashMap);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    });

                }

                @Override
                public void onUploadFailed(String code, String message) {
                    //上传失败返回错误码和message.错误码有详细的错误信息请开发者仔细阅读
                    Log.d(TAG, "onUploadFailed" + "code" + code + "message" + message);
                    UploadVedioActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            T.showShort("上传错误");
                            if (popupWindowProgress != null) {
                                popupWindowProgress.dismiss();
                            }
                        }
                    });
                }

                @Override
                public void onUploadProgress(long uploadedSize, long totalSize) {
                    //上传的进度回调,非UI线程


                    UploadVedioActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {


                            if (popupWindowProgress != null) {
                                popupWindowProgress.setTvFirst((uploadedSize * 100 / totalSize));
                            }
                        }
                    });

                    Log.d(TAG, "onUploadProgress" + uploadedSize * 100 / totalSize);
//                progress = uploadedSize * 100 / totalSize;
//                handler.sendEmptyMessage(0);
                }

                @Override
                public void onSTSTokenExpried() {
                    Log.d(TAG, "onSTSTokenExpried");
                    //STS token过期之后刷新STStoken，如正在上传将会断点续传
                    vodsVideoUploadClient.refreshSTSToken(userCenterBo.getAccessKeyId(), userCenterBo.getAccessKeySecret(), userCenterBo.getSecurityToken(), System.currentTimeMillis() + "");
                }

                @Override
                public void onUploadRetry(String code, String message) {
                    //上传重试的提醒
                    UploadVedioActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            T.showShort("请重试");
                            if (popupWindowProgress != null) {
                                popupWindowProgress.dismiss();
                            }
                        }
                    });
                    Log.d(TAG, "onUploadRetry" + "code" + code + "message" + message);
                }

                @Override
                public void onUploadRetryResume() {
                    //上传重试成功的回调.告知用户重试成功
                    Log.d(TAG, "onUploadRetryResume");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            T.showShort("请重试" + e);
        }

    }


    @Override
    public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            case 0://拍摄逻辑
                break;
            case 1://选择视频逻辑
                // 进入相册 以下是例子：用不到的api可以不写
                PictureSelector.create(UploadVedioActivity.this)
                        .openGallery(PictureMimeType.ofVideo())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                        .theme(R.style.picture_default_style1)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                        .maxSelectNum(1)// 最大图片选择数量 int
                        .minSelectNum(1)// 最小选择数量 int
                        .imageSpanCount(4)  // 每行显示个数 int
                        .isCamera(true)// 是否显示拍照按钮 true or false
                        .compress(true)// 是否压缩 true or false
                        .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                        .forResult(20005);//结果回调onActivityResult code     ;
                dialog.dismiss();
                break;
        }
    }

    private void initVedioAdapter() {

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new GridImageAdapter(this, onAddPicClickListener);
//        adapter.setList(selectList);
        adapter.setSelectMax(1);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 2:
                            // 预览视频
                            PictureSelector.create(UploadVedioActivity.this).externalPictureVideo(media.getPath());
                            break;
                    }
                }
            }
        });
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
//            dialog.show();
        }

        @Override
        public void onDeleteClick() {
            mCoverFile = null;
            mVedioFile = null;
        }
    };


    @Override
    public void showUserDataSuccess(UserCenterBo s) {

    }

    @Override
    public void showUploadHeadSuccess(String url) {
        T.showLong("上传成功");
        if (popupWindowProgress != null) {
            popupWindowProgress.dismiss();
        }
        finish();
    }

    @Override
    public void showFollowSuccess() {

    }

    @Override
    public void showUnFollowSuccess() {

    }

    @Override
    public void showError(String error) {
        T.showLong(error);
        if (popupWindowProgress != null) {
            popupWindowProgress.dismiss();
        }
    }


}
